package com.bootdo.system.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.app.common.msg.Response;
import com.bootdo.app.common.utils.DateUtil;
import com.bootdo.app.dto.wx.TemplateMsgRequest;
import com.bootdo.app.service.UserMeetingService;
import com.bootdo.app.service.WXService;
import com.bootdo.app.vo.miniprogram.UserMeetingVo;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.TbJcLog;
import com.bootdo.system.domain.TbMtlm;
import com.bootdo.system.domain.TbOrder;
import com.bootdo.system.domain.TbUserWater;
import com.bootdo.system.domain.TbWeixinconfig;
import com.bootdo.system.domain.TbWxmenu;
import com.bootdo.system.domain.TbWxuser;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.dto.MtlmDto;
import com.bootdo.system.service.MtlmService;
import com.bootdo.system.service.OrderService;
import com.bootdo.system.service.TxService;
import com.bootdo.system.service.UserLsService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.WxConfigService;
import com.bootdo.system.service.WxMenuService;
import com.bootdo.system.service.WxUserService;

@Controller
@RequestMapping("/gssq")
public class GssqGlController {
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private WXService wXService;
	
	@Autowired
	private WxUserService wxUserService;
	
	@Autowired
	private WxConfigService wxConfigService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserLsService userLsService;
	
	@Autowired
	private WxMenuService wxMenuService;
	
	@Autowired
	MtlmService mtlmService;
	
	 @Autowired
	 private UserMeetingService userMeetingService;
	 
//	 @GetMapping("/aa")
//	String welcome(Model model) { 
//		return "forward:https://w.dianping.com/cube/evoke/increase/meituan.html?lch=s:waimai:1:c85d5261e1b8b214d0706c9334a01c51:7@oPGEi5Q_rH9tRaJdY-n3MDNfMkkg&url=https%3A%2F%2Frunion.meituan.com%2Furl%3Fkey%3Dc85d5261e1b8b214d0706c9334a01c51%26url%3Dhttps%253A%252F%252Fi.meituan.com%252Fawp%252Fhfe%252Fblock%252F652c4b9d8a2425a98ca5%252F92207%252Findex.html%253Fappkey%253Dc85d5261e1b8b214d0706c9334a01c51%253A7%2540oPGEi5Q_rH9tRaJdY-n3MDNfMkkg%26sid%3D7%40oPGEi5Q_rH9tRaJdY-n3MDNfMkkg";
//	}
	 
	@ResponseBody
	@RequestMapping("/list2")
	public Response searchWjList2(HttpServletResponse resp) {
		UserMeetingVo meetingLog = userMeetingService.getMeetingLog();
		String userId = meetingLog.getUserId();
		return Response.success("cc");
	}
	

	@ResponseBody
	@RequestMapping("/list")
	public Response searchWjList(HttpServletResponse resp) {
		List<TbMtlm> list3 = mtlmService.getList3();
		for (TbMtlm tbMtlm : list3) {
			String orderid = tbMtlm.getOrderid();
			Double profit = getDouble2String(tbMtlm.getDirect());
			Double double2ratio = getDouble2String(tbMtlm.getRatio());
			profit=profit * double2ratio;
			TbOrder list2Ceshi = orderService.list2Ceshi(orderid);
			if(list2Ceshi != null) {
				list2Ceshi.setProfit2(getDouble2String2(profit+"")+"");
				orderService.insert2update(list2Ceshi);
			}
		}
		return Response.success("cc");
	}
	
	@Transactional
	@ResponseBody
	@RequestMapping("/ceshi")
	public void ceshi(HttpServletResponse resp) {
		MtlmDto table=new MtlmDto();
		table.setSmstitle("津煎.煎饼果子");
		table.setQuantity("1");
		table.setOrderid("78626881566");
		table.setDealid("7862688");
		table.setPaytime("1608164316");
		table.setType("4");
		table.setOrdertime("1608164316");
		table.setSid("3@oPGEi5bBlzy48Ivfxuz05st8mCyM");
		table.setUid("79926");
		table.setStatus("1");
		table.setTotal("31.09");
		table.setDirect("17.09");
		table.setRatio("0.06");
		table.setSign("74f24ecaf0ced144cc679028016b6b3a");
		//sid 拼接必须要   商家id+@+openId
		System.out.println(table.toString());
		
		String sid2 = table.getSid();
		if(!StringUtils.isNoneBlank(sid2)) {
			return;
		}
		String[] split = sid2.split("@");
		if(split.length != 2) {
			return;
		}
		//MtlmDto [smstitle=津煎.煎饼果子, quantity=1, orderid=78626881373166376, openId=null, dealid=7862688, paytime=1608164316, type=4, ordertime=1608164316, sid=2@oKu7n1TP38UDSwnZaBtEfI03a-ho, uid=79926, status=1, total=31.09, direct=17.09, ratio=0.06, sign=74f24ecaf0ced144cc679028016b6b3a]
		//MtlmDto [smstitle=津煎.煎饼果子, quantity=1, orderid=78626881373166376, openId=null, dealid=7862688, paytime=1608164316, type=4, ordertime=1608164316, sid=2@oKu7n1TP38UDSwnZaBtEfI03a-ho, uid=79926, status=1, total=31.09, direct=17.09, ratio=0.06, sign=74f24ecaf0ced144cc679028016b6b3a]
		//MtlmDto [smstitle=津煎.煎饼果子, quantity=1, orderid=78626881373166376, openId=null, dealid=7862688, paytime=1608164316, type=4, ordertime=1608164316, sid=2@oKu7n1TP38UDSwnZaBtEfI03a-ho, uid=79926, status=1, total=31.09, direct=17.09, ratio=0.06, sign=74f24ecaf0ced144cc679028016b6b3a]
		TbOrder byIdOid = orderService.getByIdOid(table.getOrderid(),split[1]);
		if(byIdOid != null) {
			return;
		}
		
		//1 插入美团订单表
		TbOrder double2Order = getDouble2Order(table);
		double2Order.setStatus(1);
		double2Order.setPaytime(DateUtil.formatLongDateTime(new Date()));
			
			//2佣金处理
			//佣金总金额
			Double profit = getDouble2String(table.getDirect());
			String ratio = table.getRatio();
			Double double2ratio = getDouble2String(ratio);
			double2ratio=double2ratio/100;
			profit=profit * double2ratio;
			TbWxuser userById = wxUserService.getUserById(double2Order.getOpenid());
			if(userById == null) {
				return;
			}
			
			//根据后台用户id 查询佣金比例
			String sid = userById.getSid();
			TbWeixinconfig selectByUserId = wxConfigService.selectByUserId(Integer.valueOf(sid));
			TbWxmenu selectByUserId2 = wxMenuService.selectByUserId(Integer.valueOf(sid));
			// 余额放入 后台用户余额
			UserDO userDO = userService.get(Long.valueOf(sid));
			String balanceuc = userDO.getBalance();
			Double balanceu = getDouble2String(balanceuc);
			userDO.setBalance((balanceu+profit)+"");
			userService.update4(userDO);
			//记录用户流水
			TbUserWater tbUserWater = new TbUserWater();
			//用户下单类型
			tbUserWater.setZjlx(4);
			tbUserWater.setWaterJe(profit+"");
			tbUserWater.setUserId(Long.valueOf(sid));
			tbUserWater.setOrderId(table.getOrderid());
			tbUserWater.setOrderType(1);
			userLsService.insert(tbUserWater);
			
			String tgbl = userById.getTgbl();
			if(StringUtils.isNoneBlank(tgbl)) {
				Integer valueOf = Integer.valueOf(tgbl);
				//如果有个人分配金额
				if(valueOf != null && valueOf > 0) {
					double valueOf2=getDouble2String(valueOf+"")/100;
					Double balance = getDouble2String(userById.getBalance());
					userById.setBalance((balance+(profit*valueOf2))+"");
					wxUserService.insert2update(userById);
					
					//记录用户奖励
					TbJcLog tbJcLog = new TbJcLog();
					tbJcLog.setJcje(new BigDecimal(profit*valueOf2));
					tbJcLog.setUserId(Integer.valueOf(sid));
					tbJcLog.setJczt(1);
					tbJcLog.setJcbz("美团返佣");
					wxUserService.insertJc(tbJcLog);
					
					double2Order.setProfit((profit*valueOf2)+"");
					//当前用户分配完成 插入订单
					int insert2update = orderService.insert2update(double2Order);
					
					//发送模板消息 String toUserOpenId,String url,String orderName,String orderTime,String orderMoney,String commission
					if(userById.getGzhOpenId() != null) {
						TemplateMsgRequest newUserJoin = TemplateMsgRequest.createNewOrder(userById.getGzhOpenId(),null, table.getSmstitle(), DateUtils.format(new Date()),table.getDirect(),(profit*valueOf2)+"",selectByUserId.getServiceTemplate1());
			            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin);
					}
					profit=profit - (profit*valueOf2);
				}
			}else {
				//先判断 本人佣金分成
				Integer levelthree = selectByUserId.getLevelthree();
				if(levelthree == null) {
					levelthree=0;
				}
				 double levelthree2=getDouble2String(levelthree+"")/100;
				//用户现有余额
				Double balance = getDouble2String(userById.getBalance());
				userById.setBalance((balance+(profit*levelthree2))+"");
				wxUserService.insert2update(userById);
				
				//记录用户奖励
				TbJcLog tbJcLog = new TbJcLog();
				tbJcLog.setJcje(new BigDecimal(profit*levelthree2));
				tbJcLog.setUserId(Integer.valueOf(sid));
				tbJcLog.setJczt(1);
				tbJcLog.setJcbz("美团返佣");
				wxUserService.insertJc(tbJcLog);
				
				double2Order.setProfit((profit*levelthree2)+"");
				//当前用户分配完成 插入订单
				int insert2update = orderService.insert2update(double2Order);
				
				//发送模板消息
				if(userById.getGzhOpenId() != null) {
					TemplateMsgRequest newUserJoin = TemplateMsgRequest.createNewOrder(userById.getGzhOpenId(),null, table.getSmstitle(), DateUtils.format(new Date()),table.getDirect(),(profit*levelthree2)+"",selectByUserId.getServiceTemplate1());
		            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin);
				}
				
				//减总金额
				profit=profit - (profit*levelthree2);
			}
			
			
			//处理上一级佣金
			Integer wxuserId = userById.getWxuserId();
			TbWxuser userById2 = wxUserService.getById(wxuserId);
			if(userById2 != null) {
				String tgbl2 = userById2.getTgbl();
				if(StringUtils.isNoneBlank(tgbl2)) {
					Integer tgbl2Val = Integer.valueOf(tgbl2);
					if(tgbl2Val != null && tgbl2Val > 0) {
						double tgbl2Val2=getDouble2String(tgbl2Val+"")/100;
						Double balance2 = getDouble2String(userById2.getBalance());
						userById2.setBalance((balance2+(profit*tgbl2Val2))+"");
						wxUserService.insert2update(userById2);
						
						//记录用户奖励
						TbJcLog tbJcLog = new TbJcLog();
						tbJcLog.setJcje(new BigDecimal(profit*tgbl2Val2));
						tbJcLog.setUserId(Integer.valueOf(sid));
						tbJcLog.setJczt(1);
						tbJcLog.setJcbz(userById.getNickname()+"好友返佣");
						wxUserService.insertJc(tbJcLog);
						//发送模板消息
						
						if(userById.getGzhOpenId() != null) {
							TemplateMsgRequest newUserJoin = TemplateMsgRequest.createNewOrder(userById2.getGzhOpenId(),null, table.getSmstitle(), DateUtils.format(new Date()),table.getDirect(),(profit*tgbl2Val2)+"",selectByUserId.getServiceTemplate1());
				            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin);
						}
						
						//减总金额
						profit=profit - (profit*tgbl2Val2);
					}
				}else {
					Integer leveltwo = selectByUserId.getLeveltwo();
					if(leveltwo == null) {
						leveltwo=0;
					}
					double leveltwo2=getDouble2String(leveltwo+"")/100;
					Double balance2 = getDouble2String(userById2.getBalance());
					userById2.setBalance((balance2+(profit*leveltwo2))+"");
					wxUserService.insert2update(userById2);
					
					//记录用户奖励
					TbJcLog tbJcLog = new TbJcLog();
					tbJcLog.setJcje(new BigDecimal(profit*leveltwo2));
					tbJcLog.setUserId(Integer.valueOf(sid));
					tbJcLog.setJczt(1);
					tbJcLog.setJcbz(userById.getNickname()+"好友返佣");
					wxUserService.insertJc(tbJcLog);
					//发送模板消息
					if(userById.getGzhOpenId() != null) {
						TemplateMsgRequest newUserJoin = TemplateMsgRequest.createNewOrder(userById2.getGzhOpenId(),null, table.getSmstitle(), DateUtils.format(new Date()),table.getDirect(),(profit*leveltwo2)+"",selectByUserId.getServiceTemplate1());
			            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin);
					}
					//减总金额
					profit=profit - (profit*leveltwo2);
				}
				
				//处理上二级佣金
				Integer wxuserId2 = userById2.getWxuserId();
				TbWxuser userById3 = wxUserService.getById(wxuserId2);
				if(userById3 != null) {
					String tgbl3 = userById3.getTgbl();
					if(StringUtils.isNoneBlank(tgbl3)) {
						Integer tgbl3Val = Integer.valueOf(tgbl3);
						if(tgbl3Val != null && tgbl3Val > 0) {
							double tgbl3Val2=getDouble2String(tgbl3Val+"")/100;
							Double balance3 = getDouble2String(userById3.getBalance());
							userById3.setBalance((balance3+(profit*tgbl3Val2))+"");
							wxUserService.insert2update(userById3);
							
							//记录用户奖励
							TbJcLog tbJcLog = new TbJcLog();
							tbJcLog.setJcje(new BigDecimal(profit*tgbl3Val2));
							tbJcLog.setUserId(Integer.valueOf(sid));
							tbJcLog.setJczt(1);
							tbJcLog.setJcbz(userById2.getNickname()+"好友返佣");
							wxUserService.insertJc(tbJcLog);
							//发送模板消息
							if(userById.getGzhOpenId() != null) {
								TemplateMsgRequest newUserJoin = TemplateMsgRequest.createNewOrder(userById3.getGzhOpenId(),null, table.getSmstitle(), DateUtils.format(new Date()),table.getDirect(),(profit*tgbl3Val2)+"",selectByUserId.getServiceTemplate1());
					            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin);
							}
							//减总金额
							profit=profit - (profit*tgbl3Val2);
						}
					}else {
						Integer levelone = selectByUserId.getLevelone();
						if(levelone == null) {
							levelone=0;
						}
						double levelone2=getDouble2String(levelone+"")/100;
						Double balance3 = getDouble2String(userById3.getBalance());
						userById3.setBalance((balance3+(profit*levelone2))+"");
						wxUserService.insert2update(userById3);
						
						//记录用户奖励
						TbJcLog tbJcLog = new TbJcLog();
						tbJcLog.setJcje(new BigDecimal(profit*levelone2));
						tbJcLog.setUserId(Integer.valueOf(sid));
						tbJcLog.setJczt(1);
						tbJcLog.setJcbz(userById2.getNickname()+"好友返佣");
						wxUserService.insertJc(tbJcLog);
						//发送模板消息
						if(userById.getGzhOpenId() != null) {
							TemplateMsgRequest newUserJoin = TemplateMsgRequest.createNewOrder(userById3.getGzhOpenId(),null, table.getSmstitle(), DateUtils.format(new Date()),table.getDirect(),(profit*levelone2)+"",selectByUserId.getServiceTemplate1());
				            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin);
						}
					}
				}
			}
			
			
			
	}
	private Double getDouble2String(String num) {
		if(StringUtils.isNoneBlank(num)) {
			Double cny = Double.parseDouble(num);
			DecimalFormat df = new DecimalFormat("0.00000"); 
			String CNY = df.format(cny);
			Double cny1 = Double.parseDouble(CNY);
			return cny1;
		}
		return 0.00;
	}
	
	private Double getDouble2String2(String num) {
		if(StringUtils.isNoneBlank(num)) {
			Double cny = Double.parseDouble(num);
			DecimalFormat df = new DecimalFormat("0.00"); 
			String CNY = df.format(cny);
			Double cny1 = Double.parseDouble(CNY);
			return cny1;
		}
		return 0.00;
	}
	
	private TbOrder getDouble2Order(MtlmDto table) {
		TbOrder tbOrder = new TbOrder();
		tbOrder.setTitle(table.getSmstitle());
		tbOrder.setOid(table.getOrderid());
		tbOrder.setTotal(table.getTotal());
		tbOrder.setDirect(table.getDirect());
		tbOrder.setPaytime(table.getPaytime());
		tbOrder.setSid(table.getSid());
		//媒体方id
		tbOrder.setSidName(table.getUid());
		String sid = table.getSid();
		String[] split = sid.split("@");
		tbOrder.setOpenid(split[1]);
		
		//返佣是根据总金额还是实际支付金额
		//目前使用实际支付金额
		Double ratio = getDouble2String(table.getRatio());
		Double direct = getDouble2String(table.getDirect());
		if(ratio == 0 || direct == 0) {
			tbOrder.setProfit("0");
		}else {
			Double res=ratio*direct;
			tbOrder.setProfit(res.toString());
		}
		//订单签名不知用意？
		return tbOrder;
	}

}
